import Vue from 'vue'
import VueRouter from 'vue-router'

import UserPersonInfo from "@/views/front/UserPersonInfo.vue";
import FrontTopMenu from "@/components/FrontTopMenu.vue";
import NewsDetail from "@/views/front/NewsDetail.vue";
import PostCodeDetail from "@/views/front/PostCodeDetail.vue";



// 获取原型对象push函数
const originPush = VueRouter.prototype.push
// 获取原型对象replace函数
const originReplace = VueRouter.prototype.replace

// 修改原型对象中的push函数
VueRouter.prototype.push = function push(location) {
    return originPush.call(this, location).catch(err => err)
}

// 修改原型对象中的replace函数
VueRouter.prototype.replace = function replacement(location) {
    return originReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const paths = [
    {

        path: '/login',
        meta: {isToken: false, menuName: "登录", role: []},
        name: 'login',
        component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
    },
    {
        path: '/forgetPassword',
        meta: {isToken: false, menuName: "忘记密码", role: []},
        name: 'forgetPassword',
        component: () => import(/* webpackChunkName: "about" */ '../views/ForgetPassword.vue')
    },
    {
        path: '/register',
        meta: {isToken: false, menuName: "注册", role: []},
        name: 'register',
        component: () => import(/* webpackChunkName: "about" */ '../views/Register.vue')
    },
    // 没有菜单权限
    {
        path: '/permissionDenied',
        meta: {isToken: false, menuName: "无权限", role: []},
        name: 'permissionDenied',
        component: () => import(/* webpackChunkName: "about" */ '../views/PermissionDenied.vue')
    },
    // 404
    {
        path: '/404',
        meta: {isToken: false, menuName: "暂无页面", role: []},
        name: '404',
        component: () => import(/* webpackChunkName: "about" */ '../views/404.vue')
    },
    {
        path: '/backHome',
        meta: {isToken: true, menuName: "后台首页", role: ["ROLE_TEACHER", "ROLE_ADMIN"]},
        name: 'backHome',
        component: () => import(/* webpackChunkName: "about" */ '../views/back/Home.vue')
    },
    //前台相关路由配置

    {
        path: '/frontHome',
        component: FrontTopMenu,
        meta: {isToken: true, menuName: "前台", role: ["ROLE_USER"]},
        children: [
            {
                path: '/frontHome', // 子路由的默认路径，访问 /frontHome 时会显示这个子路由对应的组件
                name: 'frontHome',
                meta: {isToken: true, menuName: "前台首页", role: ["ROLE_USER"]},
                component: () => import(/* webpackChunkName: "about" */ '../views/front/FrontHome.vue')
            },
            {
                path: '/video',
                meta: {isToken: true, menuName: "视频学习", role: ["ROLE_USER"]},
                name: 'video',
                component: () => import(/* webpackChunkName: "about" */ '../views/front/VideoLearning.vue')
            },
            {
                path: '/subject/video/:id',
                meta: {isToken: true, menuName: "课程视频", role: ["ROLE_USER"]},
                name: 'subjectVideo',
                props: true,
                component: () => import(/* webpackChunkName: "about" */ '../views/front/SubjectVideo.vue')
            },
            {
                path: '/video/details/:id',
                meta: {isToken: true, menuName: "课程详情", role: ["ROLE_USER"]},
                name: 'videoDetails',
                props: true,
                component: () => import(/* webpackChunkName: "about" */ '../views/front/VideoDetails.vue')
            },
            {
                path: '/discussion',
                meta: {isToken: true, menuName: "讨论区", role: ["ROLE_USER"]},
                name: 'discussion',
                component: () => import(/* webpackChunkName: "about" */ '../views/front/PostCode.vue')
            },
            {
                path: '/ondiscussion',
                meta: {isToken: true, menuName: "在线讨论区", role: ["ROLE_USER"]},
                name: 'ondiscussion',
                component: () => import( '../views/front/OnDiscussion.vue')
            },
            {
                path: '/competition',
                meta: {isToken: true, menuName: "赛事通知", role: ["ROLE_USER"]},
                name: 'competition',
                component: () => import(/* webpackChunkName: "about" */ '../views/front/CompetitionNotice.vue')
            },
            {
                path: '/userPersonInfo',
                meta: {isToken: true, menuName: "用户信息", role: ["ROLE_USER"]},
                name: 'userPersonInfo',
                component:UserPersonInfo
            },
            {
                path: '/news/detail/:id',
                name: 'NewsDetail',
                meta: {isToken: true, menuName: "赛事详情", role: ["ROLE_USER"]},
                component: NewsDetail
            },
            {
                path: '/discussion/detail/:id',
                name: 'PostCodeDetail',
                meta: {isToken: true, menuName: "帖子详情", role: ["ROLE_USER"]},
                component: PostCodeDetail
            },
        ]
    },
]

const router = new VueRouter({
    mode: "history",
    routes: paths
})

function Compare(property) {
    return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
    }
}

// 制定动态路由
export const setRoutes = () => {
    localStorage.removeItem("menus")
    // 从服务器里面获取菜单列表
    const storeMenus = JSON.parse(localStorage.getItem("user"))
    if (storeMenus && storeMenus.menuList) {
        // 拼装动态路由
        const backRoute = {
            path: '/',
            meta: {isToken: true, menuName: "首页"},
            name: 'home',
            //路由名称
            component: () => import('../views/back/Home.vue'),
            //路由路径
            children: []
        }
        let singleRouteArr = []
        storeMenus.menuList.forEach(item => {
            let singleRoute = ""
            singleRouteArr.push(recursionSetMenu(item, singleRoute))
        })
        backRoute.children.push(...singleRouteArr)
        //数据把设置到服务器
        backRoute.children = backRoute.children.sort(Compare("sort"))
        localStorage.setItem('menus', JSON.stringify(backRoute))
        let routeMenuChildrenList = recursionMenu(backRoute.children, [])
        backRoute.children = routeMenuChildrenList.sort(Compare("sort"))
        //获取当前的路由对象名称队列
        const currentRouteNames = router.getRoutes().map(v => v.name)
        if (!currentRouteNames.includes("home")) {
            router.addRoute(backRoute)
        }
    }
}

export const recursionMenu = function (backRouteChildren, childrenList) {
    backRouteChildren.forEach(item => {
        if (item.path) {
            childrenList.push(item)
        } else {
            recursionMenu(item.children, childrenList)
        }
    })
    return childrenList;
}

/**
 * 阶梯塞入菜单项目，生成菜单的结构
 * @param item
 * @param singleRoute
 */
export const recursionSetMenu = function (item, singleRoute) {
    let singleRouteObj = {
        path: item.path? "/" + item.path : "",
        meta: {
            isToken: item.isToken == 0? true : false,
            menuName: item.menuName,
            isShowMenu: item.isShowMenu == 0? true : false,
            icon: item.icon
        },
        name: item.name? item.name : "",
        sort: item.sort,
        children: []
    }
    if (item.filePath) {
        singleRouteObj.component = () => import(`@/views/back/${item.filePath}.vue`)
    }
    if (singleRoute) {
        singleRoute.children.push(singleRouteObj)
    } else {
        singleRoute = singleRouteObj
    }
    if (item.children && item.children.length > 0) {
        item.children.forEach(itemChildren => {
            recursionSetMenu(itemChildren, singleRoute)
        })
    }
    return singleRoute
}

//要刷新页面就要重新设置路由，否则路由就会被重置
setRoutes()

// 路由前置守卫
// 标记是否初次进行路由设置
let isInitialRouteSetup = false;
// 记录上一次的用户信息，用于对比是否有变化
let lastUserInfo = null;

router.beforeEach((to, from, next) => {
    const currentUserInfo = JSON.parse(localStorage.getItem("user"));
    // 如果当前路径是根路径 `/` 或者路径没有特定后缀（比如路径结尾不是有效页面路径），跳转到登录页面
    if (to.path === '/' || to.path.endsWith('/')) {
        return next('/login');
    }
    if (!isInitialRouteSetup || (lastUserInfo && currentUserInfo && lastUserInfo.menuList!== currentUserInfo.menuList)) {
        setRoutes();
        isInitialRouteSetup = true;
        lastUserInfo = currentUserInfo;
    }

    // 获取当前缓存中的用户信息
    let user = JSON.parse(localStorage.getItem("user"));
    // 如果是去不需要 Token 的页面直接放行
    if (JSON.stringify(to.meta)!== '{}' &&!to.meta.isToken) {
        next();
    }
    // 如果去需要 Token 的页面
    else {
        if (JSON.stringify(to.meta) === "{}") {
            if (to.path === "/") {
                next("/login");
            } else {
                next("/404");
            }
        }
        // 如果缓存内没有用户信息，则跳转到登陆页面
        if (!user) {
            next("/login");
        } else {
            next();
        }
    }
});

export default router